<?php
session_start();
if (!isset($_SESSION['loggedUsername']) or !$_SESSION['loggedUsername']) {  //说明未登录
    echo "<script>alert('本页面需要登录后才能访问，请登录！');location.href='index.php';</script>";
    exit;
}
$pw = $_POST['pw'];
$sex = $_POST['sex'];
$age = $_POST['age'];
$email = $_POST['email'];
$ren = $_POST['ren'];
$fav = implode(",", $_POST['fav']);
//完成数据更新
include_once "conn.php";
if ($_FILES['pic']['error'] == 4) {
    $pic = 0;//说明不修改头像
} else {
    if ($_FILES['pic']['error'] > 0) {  //说明用户上传了头像，且上传出错
        echo "<script>alert('上传头像出错！');history.back();</script>";
        exit;
    } else {
        //说明用户正常上传了头像
        // 允许上传的图片后缀
        $allowedExts = array("jpg", "jpeg", "gif", "png");
        $temp = explode(".", $_FILES["pic"]["name"]);//得到一个数组
        $extension = end($temp);    // 获取文件后缀名
        if ((($_FILES['pic']['type'] === "image/jif")
                || ($_FILES["pic"]["type"] == "image/jpeg")
                || ($_FILES["pic"]["type"] == "image/jpg")
                || ($_FILES["pic"]["type"] == "image/png"))
            && ($_FILES['pic']['size']) < 204800 && in_array($extension, $allowedExts)) {
            //将上传的临时文件移到指定的位置，从而完成头像的上传
            $move = iconv("utf-8", "gb2312//IGNORE", $username);
            if (move_uploaded_file($_FILES["pic"]["tmp_name"], "upload/" . $move . "." . $extension)) {
                $pic = 1;
            } else {
                echo "<script>alert('头像上传错误！');history.back();</script>";
                exit;
            }
        } else {
            print_r($_FILES['pic']['error']);
            exit;
            echo "<script>alert('头像格式错误，仅支持JPG，JPEG,PNG,GIF格式。或者文件尺寸超标 ，文件不得大于200K.');history.back();</script>";
            exit;
        }
    }
}
if ($pw) { //说明要更新密码
    $sql = "update userinfo set pw = '" . md5($pw) . "',sex = '$sex',age = '$age',email = '$email',fav = '$fav',ren = '$ren'";
    if ($pic) {  //说明要更新头像
        $sql .= ",pic = '" . $username . " " . $extension . "'";
    }
    $sql .= "where username = '" . $_SESSION['loggedUsername'] . "'";
} else { //说明不更新密码
    $sql = "update userinfo set sex = '$sex',age = '$age',email = '$email',fav = '$fav'";
    if ($pic) { //说明要更新头像
        $sql .= ",pic='" . $username . "." . $extension . "'";
    }
    $sql .= " where username = '" . $_SESSION['loggedUsername'] . "'";
}
$result = mysqli_query($conn, $sql);
if ($result) { //说明执行成功
    echo "<script>alert('资料修改成功！');location.href='index.php';</script>";
} else {
    echo "<script>alert('资料修改失败！');history.back();</script>";
}
?>